#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@author: caijj
@version: V1.0
@file: database_tool.py
@date: 2022/01/21 0026
"""
import pymssql
import pymysql


class DataBaseTool(object):

    def __init__(self, db_type='SQL_Server', database_name='JRZF_BASE'):
        if db_type == 'SQL_Server':
            db_info = {
                'server': '192.168.106.21:1433',
                'user': 'base',
                'password': 'base',
                'database': database_name,
                'charset': 'utf8'
            }
            self.conn = pymssql.connect(**db_info)
        elif db_type == 'My_SQL':
            db_info = {
                # 'host': ini.mysql_database_host,
                # 'port': int(ini.mysql_database_port),
                # 'user': ini.mysql_database_account,
                # 'password': ini.mysql_database_password,
                'database': database_name,
                'charset': 'utf8'
            }
            self.conn = pymysql.connect(**db_info)
        else:
            raise ValueError('传值错误')

    def select_sql(self, sql):
        try:
            cursor = self.conn.cursor()
            cursor.execute(sql)
            col = cursor.description
            fields = []
            for i in range(len(col)):
                fields.append(col[i][0])
            fc = cursor.fetchall()
            return fc
        except Exception as ex:
            self.conn.rollback()
            raise ex
        finally:
            self.conn.close()

    def update_sql(self, sql, data=None):
        try:
            cursor = self.conn.cursor()
            if data is None:
                count = cursor.execute(sql)
            else:
                count = cursor.execute(sql, data)
            self.conn.commit()
            return count
        except Exception as ex:
            self.conn.rollback()
            raise ex
        finally:
            self.conn.close()

    def get_column_name_sql(self, table_name):
        sql = "select COLUMN_NAME from information_schema.COLUMNS where table_name = '{table_name}'".\
                format(table_name=table_name)
        try:
            cursor = self.conn.cursor()
            cursor.execute(sql)
            col = cursor.description
            fields = []
            for i in range(len(col)):
                fields.append(col[i][0])
            fc = cursor.fetchall()
            return fc
        except Exception as ex:
            self.conn.rollback()
            raise ex
        finally:
            self.conn.close()
